package com.plum.admin.config.security.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.common.util.ResponseUtil;
import com.plum.admin.common.vo.TokenUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/8/13 16:47
 */
@Slf4j
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    private StringRedisTemplate redisTemplate;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager,StringRedisTemplate redisTemplate) {
        super(authenticationManager);
        this.redisTemplate=redisTemplate;
    }

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager, AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationManager, authenticationEntryPoint);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader(Constant.HEADER);
        if(StrUtil.isBlank(header)){
            header=request.getParameter(Constant.HEADER);
        }
        boolean noValid=StrUtil.isBlank(header)||(!header.startsWith(Constant.TOKEN_SPLIT));
        if(noValid){
            chain.doFilter(request,response);
            return;
        }
        try{
            UsernamePasswordAuthenticationToken authentication =null;
            if(StrUtil.isNotBlank(header)){
                authentication = getAuthenticationToken(header, response);
            }
            if(ObjectUtil.isNull(authentication)){
                return;
            }
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }catch (Exception e){
            log.warn(e.toString());
        }
        chain.doFilter(request,response);
    }
    private UsernamePasswordAuthenticationToken getAuthenticationToken(String header,HttpServletResponse response){
        List<GrantedAuthority> authorities = new ArrayList<>();
        String token = redisTemplate.opsForValue().get(Constant.TOKEN_PRE + header.split(" ")[1]);
        if(StrUtil.isBlank(token)){
            ResponseUtil.out(response,ResponseUtil.resultMap(401,"登录已失效"));
            return null;
        }
        TokenUser tokenUser = new Gson().fromJson(token, TokenUser.class);
        String username = tokenUser.getUsername();
        List<String> permissions = tokenUser.getPermissions();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        if(StrUtil.isNotBlank(username)){
            User user=new User(username,"",authorities);
            return new UsernamePasswordAuthenticationToken(user,null,authorities);
        }
        return null;
    }
}
